package com.dengcj.ecology.request;

import cn.hutool.db.Entity;
import com.dengcj.ecology.request.entity.NodeExecuterResult;
import weaver.general.Util;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.Row;

import java.util.*;

/**
 * @author dengchunjie
 * @Description: 节点附加操作工具类
 * @date 2022/1/10 09:55
 */
public class NodeActionUtil {

    /**
     * 从Requestinfo对象中获取主表数据，返回Entity
     * 取值示例：
     *      mainFormData.getStr("主表字段名")  获取字符串
     *      mainFormData.getInt("主表字段名")  获取整数
     *      mainFormData.getDouble("主表字段名")  获取浮点数
     * @param requestInfo 请求对象
     * @return 主表Map
     */
    public static Entity getMainFormData(RequestInfo requestInfo){
        Entity entity = new Entity();
        Arrays.stream(requestInfo.getMainTableInfo().getProperty()).forEach(property -> entity.put(property.getName(), Util.null2String(property.getValue())));

        return entity;
    }

    /**
     * 从Requestinfo对象中获取明细表数据
     * 获取明细表1的数据使用示例：
     * Map<String, List<Entity>> detailFormData = NodeActionUtil.getDetailFormData(requestInfo);
     * List<Entity> dt1List = detailFormData.get("dt1");
     * dt1List.forEach(entity -> {
     *     String content = entity.getStr("content");
     *     int count = entity.getInt("count");
     *     double price = entity.getDouble("price");
     * });
     * @param requestInfo 请求对象
     * @return 所有明细表数据
     */
    public static Map<String, List<Entity>> getDetailFormData(RequestInfo requestInfo){
        Map<String, List<Entity>> detailFormMap = new HashMap<>();
        DetailTable[] detailTables = requestInfo.getDetailTableInfo().getDetailTable();
        int detailTableLength = detailTables.length;
        for (int i=0 ;i < detailTableLength; i++) {
            DetailTable detailTable = detailTables[i];
            Row[] rows = detailTable.getRow();
            List<Entity> rowList = new ArrayList<>();
            for (Row row : rows) {
                Cell[] cells = row.getCell();
                Entity entity = new Entity();
                for (Cell cell : cells) {
                    entity.put(cell.getName(), Util.null2String(cell.getValue()));
                }

                rowList.add(entity);
            }

            detailFormMap.put("dt"+(i+1), rowList);
        }

        return detailFormMap;
    }

    public static RequestInfo executeResult(RequestInfo requestInfo, NodeExecuterResult nodeExecuterResult){
        if(!nodeExecuterResult.getStatus()){
            requestInfo.getRequestManager().setMessage(nodeExecuterResult.getMsgTitle());
            requestInfo.getRequestManager().setMessagecontent(nodeExecuterResult.getMsgHtml());
        }

        return requestInfo;
    }
}
